package business_opportunity

import (
	"context"
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/constants"
	pb "git.mycaigou.com/gfyx/micro-gfyx-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/business_opportunity"
	"git.myscrm.cn/golang/stark/v4"
)

type orderRepository struct {
}

// NewOrderRepository 构造函数
func NewOrderRepository() OrderRepositoryIface {
	return &orderRepository{}
}

func (r *orderRepository) SaveOrder(ctx context.Context, request *pb.SaveOrderRequest) (*pb.SaveOrderResponse, error) {
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		stark.Logger.Errorf(ctx, "SaveOrder-error: %+v, request: %+v", request, err)
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()

	client := pb.NewOrderServiceClient(conn)
	res, err := client.SaveOrder(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "SaveOrder-error: %+v, request: %+v", request, err)
		return nil, err
	}
	return res, nil
}

func (r *orderRepository) PreviewOrder(ctx context.Context, request *pb.PreviewOrderRequest) (*pb.PreviewOrderResponse, error) {
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		stark.Logger.Errorf(ctx, "PreviewOrder-error: %+v, request: %+v", request, err)
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()

	client := pb.NewOrderServiceClient(conn)
	res, err := client.PreviewOrder(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "PreviewOrder-error: %+v, request: %+v", request, err)
		return nil, err
	}
	return res, nil
}

func (r *orderRepository) GetOrderList(ctx context.Context, request *pb.GetOrderListRequest) (*pb.GetOrderListResponse, error) {
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetOrderList-error: %+v, request: %+v", request, err)
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()

	client := pb.NewOrderServiceClient(conn)
	res, err := client.GetOrderList(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetOrderList-error: %+v, request: %+v", request, err)
		return nil, err
	}
	return res, nil
}

func (r *orderRepository) GetOrderDetail(ctx context.Context, request *pb.GetOrderDetailRequest) (*pb.GetOrderDetailResponse, error) {
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetOrderDetail-error: %+v, request: %+v", request, err)
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()

	client := pb.NewOrderServiceClient(conn)
	res, err := client.GetOrderDetail(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetOrderDetail-error: %+v, request: %+v", request, err)
		return nil, err
	}
	return res, nil
}
